package com.ithong.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.code.kaptcha.Constants;
import com.ithong.common.api.ApiResult;
import com.ithong.jwt.JwtUtil;
import com.ithong.model.dto.LoginDTO;
import com.ithong.model.dto.RegisterDTO;
import com.ithong.model.entity.BmsPost;
import com.ithong.model.entity.UmsUser;
import com.ithong.service.BmsPostService;
import com.ithong.service.UmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.ithong.jwt.JwtUtil.USER_NAME;

@RestController
@RequestMapping("/ums/user")
public class UmsUserController extends BaseController {
    @Resource
    private UmsUserService umsUserService;
    @Resource
    private BmsPostService bmsPostService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ApiResult<Map<String, Object>> register(@Valid @RequestBody RegisterDTO dto) {
        UmsUser user = umsUserService.executeRegister(dto);
        if (ObjectUtils.isEmpty(user)) {
            return ApiResult.failed("账号注册失败");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", user);
        return ApiResult.success(map);
    }

    @PostMapping("/uuid")
    public ApiResult<Map<String, Object>> uuid() {
        String uuid = (String) redisTemplate.opsForValue().get("uuid");
        Map<String, Object> map = new HashMap<>(16);
        map.put("uuid", uuid);
        return ApiResult.success(map);
    }

    @PostMapping(value = "/login")
    public ApiResult<Map<String, String>> login(@Valid @RequestBody LoginDTO dto) {
        String vcode = dto.getVcode();
        String uuid = dto.getUuid();
        System.out.println("uuid:"+uuid);
        Map<String, String> map = new HashMap<>(16);
        String key = Constants.KAPTCHA_SESSION_KEY + uuid;
        String object = (String) redisTemplate.opsForValue().get(key);
        System.out.println(object);
        if (StringUtils.isNotBlank(object)) {
            // 输入的验证码是否和redis中一致
            if (object.equals(vcode)) {
                // 验证有效时间
                Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
                System.out.println("expire->>>" + expire);
                if (expire < 0L) {
                    map.put("code", "5000");
                    map.put("msg", "验证码已过期!");
                    return ApiResult.failed(map.get("msg"));
                }
            } else {
                map.put("code", "5001");
                map.put("msg", "输入验证码不正确!");
                return ApiResult.failed(map.get("msg"));
            }
        } else {
            map.put("code", "5000");
            map.put("msg", "验证码已过期!");
            return ApiResult.failed(map.get("msg"));
        }
        String token = umsUserService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        redisTemplate.delete(key);
        redisTemplate.delete("uuid");
        map.put("token", token);
        return ApiResult.success(map, "登录成功");
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ApiResult<UmsUser> getUser(@RequestHeader(value = USER_NAME) String userName) {
        UmsUser user = umsUserService.getUserByUsername(userName);
        return ApiResult.success(user);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResult<Object> logOut() {
        return ApiResult.success(null, "注销成功");
    }

    @GetMapping("/{username}")
    public ApiResult<Map<String, Object>> getUserByName(@PathVariable("username") String username,
                                                        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map<String, Object> map = new HashMap<>(16);
        UmsUser user = umsUserService.getUserByUsername(username);
        Assert.notNull(user, "用户不存在");
        Page<BmsPost> page = bmsPostService.page(new Page<>(pageNo, size),
                new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, user.getId()));
        map.put("user", user);
        map.put("topics", page);
        return ApiResult.success(map);
    }


    @PostMapping("/update")
    public ApiResult<UmsUser> updateUser(@RequestBody UmsUser umsUser) {
        umsUserService.updateById(umsUser);
        return ApiResult.success(umsUser);
    }
}
